<template>
  <VCard width="800px" class="mx-auto mt-10">
    <VToolbar color="primary" dark>
      <VToolbarTitle>初访预约申请</VToolbarTitle>
    </VToolbar>
    <VCardText>
      <VForm ref="formRef" v-model="formValid">
        <VTextField
          v-model="formModel.studentId"
          label="学号"
          :rules="[rules.required]"
          variant="outlined"
          color="primary"
          class="mb-4"
        />
        <VMenu v-model="showMenu" :close-on-content-click="false" transition="scale-transition" offset-y>
          <template v-slot:activator="{ props }">
            <VTextField
              v-model="displayTime"
              label="预约时间"
              readonly
              v-bind="props"
              variant="outlined"
              color="primary"
              class="mb-4"
            />
          </template>
          <VCard>
            <VDatePicker v-model="date" :min="minDate" no-title scrollable />
            <VDivider />
            <div class="d-flex pa-4 align-center">
              <VSelect
                v-model="hour"
                :items="hours"
                label="小时"
                style="width: 100px; margin-right: 16px"
                hide-details
              />
                              <span style="margin: 0 8px">:</span>
              <VSelect v-model="minute" :items="minutes" label="分钟" style="width: 100px" hide-details />
              <VSpacer />
              <VBtn color="primary" @click="setDateTime">确定</VBtn>
            </div>
          </VCard>
        </VMenu>
        <VSelect
          v-model="formModel.scheduledPlace"
          :items="places"
          label="预约地点"
          :rules="[rules.required]"
          variant="outlined"
          color="primary"
          class="mb-4"
        />

        <!-- 心理健康问卷 -->
        <VCard class="mb-4" elevation="2">
          <VCardTitle class="bg-blue-lighten-4">
            <VIcon class="mr-2">mdi-clipboard-text</VIcon>
            心理健康状况问卷
          </VCardTitle>
          <VCardText>
            <VAlert color="info" variant="outlined" class="mb-4">
              <VIcon>mdi-information</VIcon>
              请根据您最近两周的实际情况如实填写以下问卷，这将帮助我们更好地为您提供服务。
            </VAlert>
            
            <div v-for="(question, index) in questions" :key="index" class="mb-4">
              <VCard variant="outlined" class="pa-4">
                <div class="text-subtitle-1 font-weight-medium mb-3">
                  {{ index + 1 }}. {{ question.text }}
                </div>
                <VRadioGroup v-model="questionnaire[index]" inline>
                  <VRadio
                    v-for="option in question.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                    color="primary"
                  />
                </VRadioGroup>
              </VCard>
            </div>

            <!-- 紧急程度提示 -->
            <VAlert v-if="urgencyScore >= 15" type="warning" class="mt-4">
              <VIcon>mdi-alert</VIcon>
              根据您的填写情况，我们建议您尽快接受心理咨询服务。您的预约将被优先处理。
            </VAlert>
            <VAlert v-else-if="urgencyScore >= 10" type="info" class="mt-4">
              <VIcon>mdi-information</VIcon>
              我们会根据您的情况安排合适的咨询时间。
            </VAlert>
          </VCardText>
        </VCard>

        <VBtn color="primary" block @click="showConsentDialog" :disabled="!isFormComplete">确认预约</VBtn>
      </VForm>
    </VCardText>
  </VCard>

  <!-- 心理咨询知情同意书弹窗 -->
  <VDialog v-model="showConsent" max-width="800px" persistent @click:outside="closeConsentDialog">
    <VCard>
      <VToolbar color="primary" dark>
        <VToolbarTitle>心理咨询知情同意书</VToolbarTitle>
        <VSpacer />
        <VBtn icon @click="closeConsentDialog">
          <VIcon>mdi-close</VIcon>
        </VBtn>
      </VToolbar>
      <VCardText class="consent-content">
        <div class="text-body-1">
          <h3 class="text-h6 mb-4">一、评估基本信息</h3>
          <p class="mb-2"><strong>定义：</strong>初访员运用心理学知识，对学生进行初步心理评估，判断是否需要安排专业咨询师提供服务。</p>
          <p class="mb-2"><strong>目标：</strong>首次评估共同明确学生心理状况，确定是否需要进一步咨询服务。</p>
          <p class="mb-4"><strong>方式：</strong>采用线下方式进行评估。</p>

          <h3 class="text-h6 mb-4">二、双方权利义务</h3>
          <p class="mb-2"><strong>学生：</strong></p>
          <p class="mb-2"><strong>权利：</strong>知晓初访员资质、评估流程；可提问、自愿终止评估；要求保密（法定除外）。</p>
          <p class="mb-2"><strong>义务：</strong>如实提供个人信息和心理状况；如需取消或改期，需提前 24 小时告知；配合评估、尊重初访员。</p>
          <p class="mb-2"><strong>初访员：</strong></p>
          <p class="mb-2"><strong>权利：</strong>了解学生相关情况；有权在学生不配合或存在安全风险时终止评估。</p>
          <p class="mb-4"><strong>义务：</strong>公示自身资质，遵守伦理法规；对学生信息和评估内容保密（法定除外）；按约定开展评估；发现学生有伤害自己或他人风险时，及时采取干预措施并通知相关人员。</p>

          <h3 class="text-h6 mb-4">三、保密条款</h3>
          <p class="mb-2">初访员对学生的个人信息及评估内容严格保密，未经学生同意，不得向第三方披露。</p>
          <p class="mb-2"><strong>例外情况：</strong>学生有伤害自己或他人的明确计划；涉及虐童等违法犯罪行为；法律法规规定的其他需披露情况。</p>
          <p class="mb-4">如需在教学、培训等活动中使用相关案例，会对学生个人信息进行匿名处理，确保无法识别身份。</p>

          <h3 class="text-h6 mb-4">四、其他</h3>
          <p class="mb-2">本同意书一式两份，学生和初访员各执一份，具有同等效力。</p>
          <p class="mb-4">双方在评估过程中如发生争议，应首先通过友好协商解决；协商不成的，可向相关部门反映。</p>
          <p class="mb-4"><strong>学生已仔细阅读并理解本同意书全部内容，自愿接受此次心理初步评估。</strong></p>
        </div>
      </VCardText>
      <VDivider />
      <VCardActions class="pa-4">
        <VCheckbox
          v-model="agreedToConsent"
          label="我已仔细阅读并同意"
          color="primary"
          hide-details
        />
        <VSpacer />
        <VBtn color="secondary" @click="closeConsentDialog">取消</VBtn>
        <VBtn 
          color="primary" 
          @click="confirmAppointment"
          :disabled="!agreedToConsent"
        >
          确认预约
        </VBtn>
      </VCardActions>
    </VCard>
  </VDialog>

  <!-- 用户未注册弹窗 -->
  <VDialog v-model="showUserNotRegisteredDialog" max-width="400px" persistent @click:outside="closeUserNotRegisteredDialog">
    <VCard>
      <VToolbar color="error" dark>
        <VToolbarTitle>用户未注册</VToolbarTitle>
        <VSpacer />
        <VBtn icon @click="closeUserNotRegisteredDialog">
          <VIcon>mdi-close</VIcon>
        </VBtn>
      </VToolbar>
      <VCardText class="pa-4">
        <div class="text-center">
          <VIcon size="64" color="error" class="mb-4">mdi-account-alert</VIcon>
          <h3 class="text-h6 mb-2">用户未注册</h3>
          <p class="text-body-1">请重新输入学号</p>
        </div>
      </VCardText>
      <VDivider />
      <VCardActions class="pa-4">
        <VSpacer />
        <VBtn color="primary" @click="closeUserNotRegisteredDialog">
          确认
        </VBtn>
      </VCardActions>
    </VCard>
  </VDialog>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { useSnackbarStore } from '@/store/snackbarStore';
import { useNotificationStore } from '@/store/notificationStore';
import { addAppointment } from '@/api/appointment';
import { getUserByStudentId } from '@/api/user';

const router = useRouter();
const snackbarStore = useSnackbarStore();
const notificationStore = useNotificationStore();
const formRef = ref();
const formValid = ref(false);
const showMenu = ref(false);
const showConsent = ref(false);
const agreedToConsent = ref(false);
const showUserNotRegisteredDialog = ref(false);
const minDate = new Date().toISOString().substr(0, 10);

const places = [
  '心理咨询中心101室',
  '心理咨询中心102室',
  '心理咨询中心201室',
  '心理咨询中心202室'
];

const formModel = ref({
  studentId: '',
  scheduledTime: '',
  scheduledPlace: ''
});

const rules = {
  required: (v: string) => !!v || '必填项'
};

const date = ref('');
const hour = ref('08');
const minute = ref('00');
const hours = Array.from({ length: 24 }, (_, i) => String(i).padStart(2, '0'));
const minutes = Array.from({ length: 60 }, (_, i) => String(i).padStart(2, '0'));

// 心理健康问卷
const questions = ref([
  {
    text: '您最近两周的睡眠状况如何？',
    options: [
      { label: '很好', value: 0 },
      { label: '一般', value: 1 },
      { label: '较差', value: 2 },
      { label: '很差', value: 3 }
    ]
  },
  {
    text: '您最近是否经常感到焦虑或担忧？',
    options: [
      { label: '从不', value: 0 },
      { label: '偶尔', value: 1 },
      { label: '经常', value: 2 },
      { label: '总是', value: 3 }
    ]
  },
  {
    text: '您最近是否有过自伤或自杀的想法？',
    options: [
      { label: '从未有过', value: 0 },
      { label: '偶尔想过', value: 2 },
      { label: '经常想到', value: 4 },
      { label: '有具体计划', value: 6 }
    ]
  },
  {
    text: '您最近的学习或工作效率如何？',
    options: [
      { label: '很好', value: 0 },
      { label: '一般', value: 1 },
      { label: '较差', value: 2 },
      { label: '很差', value: 3 }
    ]
  },
  {
    text: '您最近是否经常感到情绪低落或绝望？',
    options: [
      { label: '从不', value: 0 },
      { label: '偶尔', value: 1 },
      { label: '经常', value: 2 },
      { label: '总是', value: 3 }
    ]
  },
  {
    text: '您最近与他人的关系状况如何？',
    options: [
      { label: '很好', value: 0 },
      { label: '一般', value: 1 },
      { label: '较差', value: 2 },
      { label: '很差', value: 3 }
    ]
  },
  {
    text: '您最近是否有过恐慌发作的经历？',
    options: [
      { label: '从未有过', value: 0 },
      { label: '偶尔', value: 1 },
      { label: '经常', value: 2 },
      { label: '频繁', value: 3 }
    ]
  },
  {
    text: '您目前的生活压力程度如何？',
    options: [
      { label: '很轻', value: 0 },
      { label: '一般', value: 1 },
      { label: '较重', value: 2 },
      { label: '很重', value: 3 }
    ]
  }
]);

const questionnaire = ref(new Array(questions.value.length).fill(null));

// 计算紧急程度分数
const urgencyScore = computed(() => {
  return questionnaire.value.reduce((sum, answer) => sum + (answer || 0), 0);
});

// 检查表单是否完整
const isFormComplete = computed(() => {
  return formModel.value.studentId && 
         formModel.value.scheduledTime && 
         formModel.value.scheduledPlace &&
         questionnaire.value.every(answer => answer !== null);
});

function formatDateToYMD(dateObj: string | Date) {
  const d = new Date(dateObj);
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

const displayTime = computed(() => {
  if (!formModel.value.scheduledTime) return '';
  return formModel.value.scheduledTime;
});

const setDateTime = () => {
  if (!date.value) return;
  const dateStr = formatDateToYMD(date.value);
  formModel.value.scheduledTime = `${dateStr} ${hour.value}:${minute.value}:00`;
  showMenu.value = false;
};

function getNowFormat() {
  const now = new Date();
  const y = now.getFullYear();
  const m = String(now.getMonth() + 1).padStart(2, '0');
  const d = String(now.getDate()).padStart(2, '0');
  const h = String(now.getHours()).padStart(2, '0');
  const min = String(now.getMinutes()).padStart(2, '0');
  return `${y}-${m}-${d} ${h}:${min}:00`;
}

const showConsentDialog = () => {
  // 检查所有必填字段是否已填写
  if (!formModel.value.studentId.trim()) {
    snackbarStore.showMessage('请输入学号');
    return;
  }
  
  if (!formModel.value.scheduledTime.trim()) {
    snackbarStore.showMessage('请选择预约时间');
    return;
  }
  
  if (!formModel.value.scheduledPlace.trim()) {
    snackbarStore.showMessage('请选择预约地点');
    return;
  }
  
  // 所有字段都已填写，显示知情同意书弹窗
  showConsent.value = true;
};

const closeConsentDialog = () => {
  showConsent.value = false;
  agreedToConsent.value = false;
};

const closeUserNotRegisteredDialog = () => {
  showUserNotRegisteredDialog.value = false;
  // 关闭知情同意书弹窗
  showConsent.value = false;
  agreedToConsent.value = false;
  // 清空学号
  formModel.value.studentId = '';
};

const confirmAppointment = async () => {
  if (!agreedToConsent.value) {
    snackbarStore.showMessage('请先阅读并同意知情同意书');
    return;
  }
  
  // 先验证用户是否存在
  try {
    const { data: userRes } = await getUserByStudentId(formModel.value.studentId);
    if (!userRes.success) {
      // 用户不存在，显示弹窗
      showUserNotRegisteredDialog.value = true;
      return;
    }
  } catch (e) {
    // 用户不存在，显示弹窗
    showUserNotRegisteredDialog.value = true;
    return;
  }
  
  // 用户存在，提交预约
  const applyTime = getNowFormat();
  const appointmentData = {
    studentId: formModel.value.studentId,
    scheduledTime: formModel.value.scheduledTime,
    scheduledPlace: formModel.value.scheduledPlace,
    applyTime,
    questionnaire: questionnaire.value,
    urgencyScore: urgencyScore.value,
    isUrgent: urgencyScore.value >= 15
  };
  
  try {
    const { data: res } = await addAppointment(appointmentData);
    if (res.success) {
      const urgentMessage = urgencyScore.value >= 15 ? '（紧急预约，将优先处理）' : '';
      snackbarStore.showMessage(`您已完成预约${urgentMessage}`);
      // 添加通知
      notificationStore.addAppointmentNotification(
        `学号 ${formModel.value.studentId} 的初访预约申请已提交，请等待审核${urgentMessage}`,
        '/appointment-management',
        formModel.value.studentId
      );
      closeConsentDialog();
      
      // 跳转到主页面
      router.push('/main');
    } else {
      // 显示后端返回的具体错误信息
      snackbarStore.showMessage(res.message || '预约失败，请重试');
    }
  } catch (e: any) {
    // 显示后端返回的具体错误信息
    const errorMessage = e.response?.data?.message || '预约失败，请重试';
    snackbarStore.showMessage(errorMessage);
  }
};


</script>

<style scoped>
.consent-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 20px;
}

.consent-content h3 {
  color: #1976d2;
  font-weight: 600;
  margin-top: 16px;
}

.consent-content p {
  line-height: 1.6;
  margin-bottom: 8px;
}

.consent-content strong {
  color: #333;
}
</style> 